package com.ch.android.lookforkotlinv2.vm

import android.app.Application
import android.util.Log
import android.view.View
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.ch.android.networklib.ApiException
import com.ch.android.networklib.RequestClient
import com.ch.android.networklib.data.API_STATUS_OK
import com.ch.android.networklib.data.BaseResultData
import com.ch.android.networklib.data.UserLoginData
import com.ch.android.networklib.data.UserLoginReq
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

/**
 * Author: conghao
 * Date: 2023/12/29 15:33
 * Description: UserLoginModel
 */
class UserLoginModel(application: Application) : AndroidViewModel(application) {
    val username = MutableLiveData("ch1")
    val password = MutableLiveData("123456")
    val title = MutableLiveData("未登录")
    val isLoginEnable = MutableLiveData(true)
    val userLoginData = MutableLiveData<BaseResultData<UserLoginData?>>()
    val error = MutableLiveData<Throwable>()

    init {
//        username.observe(this.getApplication()) {
//            enableLoginBtn()
//        }
//        password.observe(this.getApplication()) {
//            enableLoginBtn()
//        }
    }

    private fun enableLoginBtn() {
        isLoginEnable.value = username.value!!.trim().isNotEmpty() && password.value!!.trim().isNotEmpty()
    }

    fun onClickLogin(view: View) {
        viewModelScope.launch(Dispatchers.IO) {
            login()
        }
    }

    private suspend fun login() {
        val userLoginReq = UserLoginReq(userName = username.value!!.trim(), passwd = password.value!!.trim())
        try {
            val data = RequestClient.getApiService(getApplication()).userLogin(userLoginReq)
            data.let {
                if (it.status == API_STATUS_OK) {
                    withContext(Dispatchers.Main) {
//                        userLoginData.value = data
                        userLoginData.value = data
                        title.value = "已登录"
                    }
                } else {
                    throw ApiException(data)
                }
            }
        } catch (e: Exception) {
            withContext(Dispatchers.Main) {
                error.value = e
            }
        }
    }

    override fun onCleared() {
        super.onCleared()
        Log.d("UserLoginModel", "onCleared")
    }
}